package com.cty._02_HighQualityCode._24_ReverseList;

/**
 * @Auther: cty
 * @Date: 2020/7/9 10:08
 * @Description: 面试题24：反转链表
 * 题目：定义一个函数，输入一个链表的头结点，反转该链表并输出反转后链表的头结点。
 * @version: 1.0
 */
public class ReverseList {

    private ListNode first;

    public ReverseList(){
        first = null;
    }

    public boolean isEmpty(){
        return first == null;
    }

    public void displayList(){
        ListNode current = first;
        while(current != null){
            System.out.print(current.key + " ");
            current = current.next;
        }
        System.out.println();
    }

    public void insertFirst(ListNode node){
        node.next = first;
        first = node;
    }

    public void reverse(){
        ListNode previous = null;
        ListNode current = first;
        ListNode next = null;

        while(current != null){
            next = current.next;
            if(next == null)
                first = current;

            current.next = previous;

            previous = current;
            current = next;
        }
    }  // end reverse()

}  // end class

class ListNode{
    int key;
    ListNode next;

    public ListNode(){}

    public ListNode(int key){
        this.key = key;
    }

}  // end class
